﻿using DataModels.Dto;
using DataModels.Dto.Home;
using DataModels.Entities.AuthCore;
using DataModels.Entities.Base;
using DataModels.Entities.HomeService;
using DataModels.Enums.Home;
using Services.Payment;
using SqlSugar;
using System.Data;
using Utils;
using static DataModels.Enums.GeneralEnum;

namespace Services.Home
{
    public class HomeService(SqlSugarClient db, PaymentCenterService paymentCenterService) : BaseService(db)
    {
        private readonly ServiceTimeManagementService _serviceTimeService = new();
        protected readonly PaymentCenterService _paymentCenterService = paymentCenterService;
        /// <summary>
        /// 获取商品分类列表
        /// </summary>
        /// <returns></returns>
        public ResponseModel GetProductCategory()
        {
            var res = db.Queryable<HomeServiceProductCategory>()
                .LeftJoin<HomeServiceProductCategorySub>((pc, pcs) => pc.UUID == pcs.HomeServiceProductCategoryUUID)
                .OrderBy((pc, pcs) => pc.Sort)
                .OrderBy((pc, pcs) => pcs.Sort)
                .Select((pc, pcs) => new
                {
                    CategoryId = pc.UUID,
                    CategoryName = pc.Name,
                    CategoryUrl = pc.Url,
                    SubCategoryUrl = pcs.Url,
                    SubCategoryId = pcs == null ? Guid.Empty : pcs.UUID,
                    SubCategoryName = pcs == null ? "" : pcs.Name
                })
                .ToList()
                .GroupBy(x => new { x.CategoryId, x.CategoryName, x.CategoryUrl })
                .Select(g => new
                {
                    UUID = g.Key.CategoryId,
                    Name = g.Key.CategoryName,
                    CategoryUrl = g.Key.CategoryUrl,
                    SubCategories = g.Select(x => new
                    {
                        UUID = x.SubCategoryId,
                        Name = x.SubCategoryName,
                        x.SubCategoryUrl
                    }).Where(sc => !string.IsNullOrEmpty(sc.Name)).ToList()
                })
                .ToList();

            return Success(res);
        }

        /// <summary>
        /// 获取商品列表
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public ResponseModel GetProduct(GetProductInfo info)
        {
            int total = 0;
            // 分页查询商品基础信息（仅 UUID）
            var productPage = db.Queryable<HomeServiceProduct, HomeServiceProductSpecification, HomeServiceProductCategorySub, HomeServiceProductGroupActivity>(
                (p, ps, psc, hspga) => new JoinQueryInfos(
                    JoinType.Inner, p.UUID == ps.HomeServiceProductUUID && ps.IsDeleted == Status.Disable,
                    JoinType.Inner, psc.UUID == p.HomeServiceProductCategoryUUID,
                    JoinType.Left, hspga.HomeServiceProductUUID == p.UUID 
                        && hspga.GroupStatus == GroupstartendStatus.activities
                        && hspga.IsDeleted == Status.Disable
                        && hspga.EndTime > DateTime.Now
                ))
                .Where(p => p.IsDeleted == Status.Disable)
                // 推荐/精选
                .WhereIF(info.IsRecommend.HasValue, p => p.IsRecommend == info.IsRecommend)
                // 指定分类
                .WhereIF(info.CategoryUUID.HasValue, (p, ps, psc) => psc.HomeServiceProductCategoryUUID == info.CategoryUUID)
                // 指定子分类
                .WhereIF(info.SubCategoryUUID.HasValue, (p, ps, psc) => psc.UUID == info.SubCategoryUUID)
                // 模糊搜标题
                .WhereIF(!string.IsNullOrEmpty(info.SearchWord), p => p.Title.Contains(info.SearchWord))
                .WhereIF(info.IsGroup.HasValue && info.IsGroup == Status.Enable, (p, ps, psc, hspga) => hspga.UUID != Guid.Empty)
                .GroupBy(p => p.UUID)
                .OrderBy(p => p.CreateTime,OrderByType.Desc)
                .Select(p => p.UUID)
                .ToPageList(info.PageNumber, info.PageSize, ref total);

            if (productPage.Count == 0)
            {
                return PageSuccess();
            }

            // 获取商品最小规格价格（子查询）
            //var minPriceSubQuery = db.Queryable<HomeServiceProductSpecification>()
            //    .Where(spec => spec.IsDeleted == Status.Disable && productPage.Contains(spec.HomeServiceProductUUID))
            //    .GroupBy(spec => spec.HomeServiceProductUUID)
            //    .Select(spec => new
            //    {
            //        ProductUUID = spec.HomeServiceProductUUID,
            //        MinPrice = SqlFunc.AggregateMin(spec.Price)
            //    });

            //获取商品最小规格价格（子查询）- 包括拼团价格
            var minPriceSubQuery = db.Queryable<HomeServiceProductSpecification, HomeServiceProductGroupActivity>((spec, spga) => new JoinQueryInfos(
                    JoinType.Left,
                    spec.HomeServiceProductUUID == spga.HomeServiceProductUUID
                    && spga.GroupStatus == GroupstartendStatus.activities
                    && spga.IsDeleted == Status.Disable
                    && spga.EndTime > DateTime.Now
                ))
                .Where(spec => spec.IsDeleted == Status.Disable && productPage.Contains(spec.HomeServiceProductUUID))
                .GroupBy(spec => spec.HomeServiceProductUUID)
                .Select((spec, spga) => new
                {
                    ProductUUID = spec.HomeServiceProductUUID,
                    // 使用SqlFunc.IF判断是否有有效拼团价格
                    MinPrice = SqlFunc.AggregateMin(SqlFunc.IIF(spga.UUID != Guid.Empty, spec.GroupPrice, spec.Price)),
                    IsGroup = SqlFunc.IIF(spga.UUID != Guid.Empty, Status.Enable, Status.Disable)
                });

            // 获取商品标签列表
            var productTags = db.Queryable<HomeServiceProductTagMap>()
                .LeftJoin<HomeServiceProductTag>((map, tag) => map.HomeServiceProductTagUUID == tag.UUID)
                .Where((map, tag) => productPage.Contains(map.HomeServiceProductUUID) && map.Status == Status.Enable)
                .Select((map, tag) => new
                {
                    ProductUUID = map.HomeServiceProductUUID,
                    TagName = tag.Name
                })
                .ToList();

            // 构建商品ID到标签列表的映射
            var tagMap = productTags
                .GroupBy(t => t.ProductUUID)
                .ToDictionary(g => g.Key, g => g.Select(t => t.TagName).ToList());


            // 主查询
            var products = db.Queryable<HomeServiceProductCategorySub, HomeServiceProduct>(
                    (hspsc, hsp) => new JoinQueryInfos(
                        JoinType.Inner, hspsc.UUID == hsp.HomeServiceProductCategoryUUID
                    ))
                .LeftJoin(minPriceSubQuery, (hspsc, hsp, minPriceQ) => hsp.UUID == minPriceQ.ProductUUID)
                .Where((hspsc, hsp) => hsp.IsDeleted == Status.Disable && productPage.Contains(hsp.UUID))
                .GroupBy((hspsc, hsp, minPriceQ) => new
                {
                    ProductUUID = hsp.UUID,
                    hsp.Title,
                    hsp.ImageUrl,
                    hsp.IsRecommend,
                    minPriceQ.MinPrice
                })
                .Select((hspsc, hsp, minPriceQ) => new GetProductDto()
                {
                    UUID = hsp.UUID,
                    Title = hsp.Title,
                    Supplier = hsp.Supplier,
                    ImageUrl = hsp.ImageUrl,
                    IsRecommend = hsp.IsRecommend,
                    Price = minPriceQ.MinPrice,
                    IsGroup = minPriceQ.IsGroup,
                    Tags = new List<string>()
                }).ToList();

            // 关联标签
            foreach (var product in products)
            {
                if (tagMap.TryGetValue(product.UUID, out var tags))
                {
                    product.Tags = tags;
                }
            }
            return PageSuccess(info.PageNumber, info.PageSize, total, products);
        }

        /// <summary>
        /// 获取商品详情
        /// </summary>
        /// <param name="ProductUUID"></param>
        /// <returns></returns>
        public ResponseModel GetProductDetail(Guid ProductUUID)
        {
            //var ts = _serviceTimeService.GetAvailableTimeSlotsInRange(db, ProductUUID, DateTime.Now, DateTime.Now.AddDays(7));
            GetProductDetailDto res = db.Queryable<HomeServiceProduct, HomeServiceProductSpecification, HomeServiceProductGroupActivity>(
                (p, ps, spga) => new JoinQueryInfos(
                    JoinType.Inner, p.UUID == ps.HomeServiceProductUUID && ps.IsDeleted == Status.Disable,
                    JoinType.Left,
                    ps.HomeServiceProductUUID == spga.HomeServiceProductUUID
                    && spga.GroupStatus == GroupstartendStatus.activities
                    && spga.IsDeleted == Status.Disable
                    && spga.EndTime > DateTime.Now
                ))
                .Where(p => p.UUID == ProductUUID)
                .Where(p => p.IsDeleted == Status.Disable)
                .Select((p, ps, spga) => new GetProductDetailDto
                {
                    UUID = p.UUID,
                    Title = p.Title,
                    Subtitle = p.Subtitle,
                    Description = p.Description,
                    IsRecommend = p.IsRecommend,
                    Supplier = p.Supplier,
                    IsGroup = SqlFunc.IIF(spga.UUID != Guid.Empty, Status.Enable, Status.Disable),
                    GroupEndTime = spga.EndTime,
                    GroupCount = spga.GroupCount,
                    MaxGroupCount = spga.MaxGroupCount
                })
                .First()
                ;

            // 获取商品规格价格
            List<SpecificationTto> Specifications = db.Queryable<HomeServiceProductSpecification, HomeServiceProductGroupActivity>((spec, spga) => new JoinQueryInfos(
                    JoinType.Left,
                    spec.HomeServiceProductUUID == spga.HomeServiceProductUUID
                    && spga.GroupStatus == GroupstartendStatus.activities
                    && spga.IsDeleted == Status.Disable
                    && spga.EndTime > DateTime.Now
                ))
                .Where(spec => spec.IsDeleted == Status.Disable && spec.HomeServiceProductUUID == ProductUUID)
                .Select((spec, spga) => new SpecificationTto
                {
                    SpecificationUUID = spec.UUID,
                    Price = spec.Price,
                    GroupPrice = SqlFunc.IIF(spga.UUID != Guid.Empty, spec.GroupPrice, spec.Price),
                    OriginalPrice = spec.OriginalPrice,
                    Name = spec.Name,
                    Unit = spec.Unit,
                    Count = spec.Count,
                })
                .ToList()
                ;

            // 获取商品标签列表
            List<ProductTagDto> productTags = db.Queryable<HomeServiceProductTagMap>()
                .LeftJoin<HomeServiceProductTag>((map, tag) => map.HomeServiceProductTagUUID == tag.UUID)
                .Where((map, tag) => map.HomeServiceProductUUID == ProductUUID && map.Status == Status.Enable)
                .Select((map, tag) => new ProductTagDto
                {
                    Name = tag.Name,
                    Description = tag.Description
                })
                .ToList();

            int DealtQuantity = db.Queryable<HomeServiceOrder>()
                .Where(o => o.ProductUUID == ProductUUID)
                .Where(o => o.OrderStatus == DataModels.Enums.Home.HomeServcieOrderStatus.Completed)
                .Select(o => SqlFunc.AggregateSum(o.Count))
                .First()
                ;

            //res.TimeSlot = ts;
            res.ImageUrls = GetAttachment(ProductUUID);
            res.Tags = productTags;
            res.Specifications = Specifications;
            res.DealtQuantity = DealtQuantity;
            return Success(res);
        }

        /// <summary>
        /// 提交订单
        /// </summary>
        /// <returns></returns>
        public async Task<ResponseModel> SubmitOrder(SubmitOrderInfo info)
        {
            try
            {
                await db.BeginTranAsync();
                // 检查商品是否存在且未下架

                // 原子化更新库存并检查
                int rowsAffected = await db.Ado.ExecuteCommandAsync(
                    @"UPDATE HomeServiceProductSpecification 
              SET Count = Count - @Count, 
                  UpdateTime = @UpdateTime, 
                  UpdateUserUUID = @UpdateUserUUID 
              WHERE UUID = @UUID 
                AND HomeServiceProductUUID = @ProductUUID
                AND Count >= @Count 
                AND IsDeleted = @IsDeleted",
                    new
                    {
                        Count = info.Count,
                        UpdateTime = DateTime.Now,
                        UpdateUserUUID = UserUUID,
                        ProductUUID = info.ProductUUID,
                        UUID = info.SpecificationUUID,
                        IsDeleted = Status.Disable
                    }
                );

                if (rowsAffected == 0)
                {
                    await db.RollbackTranAsync();
                    return Error("库存不足或商品已下架");
                }
                // 获取地址
                var da = await db.Queryable<DeliveryAddress>().Where(da => da.UUID == info.AddressUUID).FirstAsync();
                if (da == null)
                {
                    return Error("地址不存在，请重新选择地址。");
                }

                // 创建预约
                HomeServiceBooking hsb = new()
                {
                    ProductUUID = info.ProductUUID,
                    //RuleUUID = info.ProductTimeRuleUUID,
                    ServiceDate = info.ServiceDate,
                    StartTime = info.StartTime,
                    EndTime = info.EndTime,
                    UserID = UserUUID,
                    ContactName = da.ContactPerson,
                    ContactPhone = da.ContactPhone,
                };

                Guid hsbuuid = await _serviceTimeService.CreateHomeServiceBookingAsync(db, hsb);


                // 获取最新商品信息用于计算金额
                var hsps = await db.Queryable<HomeServiceProductSpecification>()
                            .Where(s => s.UUID == info.SpecificationUUID)
                            .FirstAsync();

                decimal orderAmount;
                Guid hsouuid = Guid.NewGuid();
                // 拼团订单
                if (info.JoinGroup == Status.Enable)
                {
                    HomeServiceProductGroupParticipant ckhspgp = ProductGroup(info, hsouuid);
                    orderAmount = (hsps.GroupPrice != 0 ? hsps.GroupPrice : hsps.Price) * info.Count;
                }
                else
                {
                    orderAmount = hsps.Price * info.Count;
                }

                // --------- 优惠----------//
                decimal discountAmount = 0; // 优惠逻辑未实现
                // --------- 优惠----------//


                TimeSpan.TryParse(hsb.StartTime, out TimeSpan timeSpan);

                // 创建订单
                HomeServiceOrder hso = new()
                {
                    UUID = hsouuid,
                    ProductUUID = info.ProductUUID,
                    ProductSpecificationUUID = info.SpecificationUUID,
                    Count = info.Count,
                    OrderAmount = orderAmount,
                    DiscountAmount = discountAmount,
                    Address = da.GetFullAddress(),
                    ContactPerson = da.ContactPerson,
                    ContactPhone = da.ContactPhone,
                    ServiceStartTime = hsb.ServiceDate.Date.Add(timeSpan),
                    Remark = info.Remark,
                    CreateUserUUID = UserUUID,
                    CreateTime = DateTime.Now,
                    IsGroup = info.JoinGroup
                };

                hso = await db.Insertable(hso).ExecuteReturnEntityAsync();

                // 关联图片
                foreach (string url in info.ImageUrls)
                {
                    Attachment temp = new Attachment()
                    {
                        BusinessId = hso.UUID,
                        Url = url,
                        CreatedBy = UserUUID
                    };
                    await db.Insertable(temp).ExecuteCommandAsync();
                }

                // 关联预约和订单
                await db.Updateable<HomeServiceBooking>()
                  .SetColumns(b => new HomeServiceBooking { OrderUUID = hso.UUID })
                  .Where(hsb => hsb.UUID == hsbuuid)
                  .ExecuteCommandAsync();

                await db.CommitTranAsync();
                return Success(hso);
            }
            catch (MSGException ex)
            {
                await db.RollbackTranAsync();
                return Error(ex.Message);
            }
            catch (Exception ex)
            {
                await db.RollbackTranAsync();
                return Error("提交订单失败，请稍后重试。");
            }
            finally
            {
                db.Dispose();
            }
        }

        private HomeServiceProductGroupParticipant ProductGroup(SubmitOrderInfo info, Guid hsouuid)
        {
            // 查找拼团活动
            HomeServiceProductGroupActivity hspga = db.Queryable<HomeServiceProductGroupActivity>()
                .Where(hspga => hspga.IsDeleted == Status.Disable)
                .Where(hspga => hspga.GroupStatus == GroupstartendStatus.activities)
                .Where(hspga => hspga.EndTime > DateTime.Now)
                .First()
                ;
            if (hspga == null)
            {
                throw new MSGException("没有正在进行的拼团活动");
            }
            List<HomeServiceProductGroupParticipant> ckhspgp = db.Queryable<HomeServiceProductGroupParticipant>()
                .Where(hspgp => hspgp.HomeServiceProductGroupActivityUUID == hspga.UUID)
                .Where(hspgp => hspgp.Status == GroupParticipantStatus.PendingPayment ||
                    hspgp.Status == GroupParticipantStatus.Paid ||
                    hspgp.Status == GroupParticipantStatus.GroupSuccess ||
                    hspgp.Status == GroupParticipantStatus.Completed)
                .Where(hspgp => hspgp.ExpireTime > DateTime.Now)
                .Where(hspgp => hspgp.GroupDate == info.ServiceDate.Date)
                .ToList()
                ;
            if (ckhspgp.Count + 1 > hspga.MaxGroupCount)
            {
                throw new MSGException("已达到拼团上限");
            }
            TimeSpan.TryParse(info.EndTime, out TimeSpan timeSpan);

            HomeServiceProductGroupParticipant hspgp = new()
            {
                HomeServiceProductGroupActivityUUID = hspga.UUID,
                UserUUID = UserUUID,
                ExpireTime = DateTime.Now.AddMilliseconds(15), //未付款，15分钟过期
                HomeServiceOrderUUID = hsouuid,
                HomeServiceProductUUID = info.ProductUUID,
                GroupDate = info.ServiceDate.Date,
                CreateTime = DateTime.Now,
                CreateUserUUID = UserUUID
            };
            return db.Insertable(hspgp).ExecuteReturnEntity();
        }


        /// <summary>
        /// 付款订单
        /// </summary>
        /// <returns></returns>
        public ResponseModel OrderPayment(Guid OrderUUID, PayWay way)
        {
            try
            {
                db.BeginTran();
                HomeServiceOrder hso = db.Queryable<HomeServiceOrder>()
                    .Where(hso => hso.IsDeleted == Status.Disable)
                    .Where(hso => hso.UUID == OrderUUID)
                    .Where(hso => hso.OrderStatus == DataModels.Enums.Home.HomeServcieOrderStatus.PendingPayment)
                    .First();
                if (hso == null)
                {
                    return Error("未找到待支付的订单");
                }
                //_paymentCenterService.CreateBill(Guid.NewGuid(),BusinessType.HomeServicePay, way,)

                //未实现付款逻辑，假设付款成功
                hso.OrderStatus = DataModels.Enums.Home.HomeServcieOrderStatus.Completed;
                hso.PayAmount = hso.OrderAmount; // 假设全额付款
                hso.ExpireTime = null; // 取消过期时间
                hso.UpdateTime = DateTime.Now;
                hso.UpdateUserUUID = UserUUID;
                db.Updateable(hso).ExecuteCommand();

                if (hso.IsGroup == Status.Enable)
                {
                    HomeServiceProductGroupParticipant hspgp = db.Queryable<HomeServiceProductGroupParticipant>()
                        .Where(hspgp => hspgp.UserUUID == UserUUID)
                        .Where(hspgp => hspgp.HomeServiceOrderUUID == hso.UUID)
                        .First()
                        ;

                    HomeServiceBooking hsb = db.Queryable<HomeServiceBooking>()
                        .Where(hsb => hsb.IsDeleted == Status.Disable)
                        .Where(hsb => hsb.OrderUUID == hso.UUID)
                        .First()
                        ;

                    // 更新拼团状态和过期时间，过期时间为服务预约时间段结束时间
                    TimeSpan.TryParse(hsb.EndTime, out TimeSpan timeSpan);

                    hspgp.Status = GroupParticipantStatus.Paid;
                    hspgp.ExpireTime = hsb.ServiceDate.Date.Add(timeSpan);

                    db.Updateable(hspgp).ExecuteCommand();
                }
                db.CommitTran();
                return Success("付款成功，逻辑未实现，现在默认成功");
            }
            catch (Exception)
            {
                db.RollbackTran();
                return Error("付款失败，请稍后重试。");
            }
        }

        /// <summary>
        /// 发表评论
        /// </summary>
        /// <returns></returns>
        public ResponseModel SubmitOrderComment(SubmitOrderComment info)
        {
            try
            {
                db.BeginTran();

                HomeServiceOrder ckhso = db.Queryable<HomeServiceOrder>()
                    .Where(hso => hso.IsDeleted == Status.Disable)
                    .Where(hso => hso.UUID == info.OrderUUID)
                    .Where(hso => hso.OrderStatus == HomeServcieOrderStatus.Completed)
                    .First()
                    ;

                if (ckhso == null)
                {
                    return Error("订单不存在或未完成");
                }
                ckhso.OrderStatus = HomeServcieOrderStatus.IsComment;
                ckhso.UpdateTime = DateTime.Now;
                ckhso.UpdateUserUUID = UserUUID;
                db.Updateable(ckhso).ExecuteCommand();

                HomeServiceOrderComment ckhsoc = db.Queryable<HomeServiceOrderComment>()
                    .Where(hsoc => hsoc.OrderUUID == info.OrderUUID && hsoc.IsDeleted == Status.Disable)
                    .First()
                    ;
                if (ckhsoc != null)
                {
                    return Error("订单已评论，请勿重复评论");
                }

                HomeServiceOrderComment hsoc = new()
                {
                    OrderUUID = info.OrderUUID,
                    ProductUUID = ckhso.ProductUUID, // 关联的商品UUID
                    UserUUID = UserUUID,
                    UserName = UserName,
                    StarRating = info.StarRating, // 默认五星
                    Content = info.Text,
                    CreateTime = DateTime.Now
                };
                HomeServiceOrderComment rehsoc = db.Insertable(hsoc).ExecuteReturnEntity();

                foreach (var url in info.Urls)
                {
                    Attachment ac = new Attachment()
                    {
                        BusinessId = rehsoc.UUID,
                        Url = url,
                        CreatedAt = DateTime.Now,
                        CreatedBy = UserUUID
                    };
                    db.Insertable(ac).ExecuteCommand();
                }
                db.CommitTran();
                return Success("评论成功");
            }
            catch (Exception)
            {
                db.RollbackTran();
                return Error("评论失败");
            }
        }

        /// <summary>
        /// 获取评论
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public ResponseModel GetOrderComment(GetOrderCommentInfo info)
        {
            try
            {
                int total = 0;
                var query = db.Queryable<HomeServiceOrderComment>()
                    .Where(hsoc => hsoc.IsDeleted == Status.Disable)
                    .Where(hsoc => hsoc.ProductUUID == info.ProductUUID)
                    .WhereIF(info.sr.Count > 0, hsoc => info.sr.Contains(hsoc.StarRating));

                // 图片筛选
                if (info.FilterImages == Status.Enable)
                {
                    query = query.Where(hsoc => db.Queryable<Attachment>()
                        .Where(a => a.BusinessId == hsoc.UUID && a.Status == Status.Enable)
                        .Count() > 0);
                }

                var data = query
                    .Select(hsoc => new GetOrderCommentDto
                    {
                        UUID = hsoc.UUID,
                        UserUUID = hsoc.UserUUID,
                        UserName = hsoc.UserName,
                        StarRating = hsoc.StarRating,
                        Content = hsoc.Content,
                        CreateTime = hsoc.CreateTime,
                    })
                    .OrderByDescending(hsoc => hsoc.CreateTime) // 添加排序
                    .ToPageList(info.PageNumber, info.PageSize, ref total);

                foreach (var item in data)
                {
                    item.ImageUrls = GetAttachment(item.UUID);
                }

                return PageSuccess(info.PageNumber, info.PageSize, total, data);
            }
            catch (Exception ex)
            {
                return Error("获取评论失败，请稍后重试");
            }
        }

        /// <summary>
        /// 获取评论综合信息
        /// </summary>
        /// <param name="productUUID"></param>
        /// <returns></returns>
        public ResponseModel GetCommentStatistics(Guid productUUID)
        {
            try
            {
                var query = db.Queryable<HomeServiceOrderComment>()
                    .Where(hsoc => hsoc.IsDeleted == Status.Disable)
                    .Where(hsoc => hsoc.ProductUUID == productUUID);

                List<Guid> hsocuuids = query.Select(x => x.UUID).ToList();

                int ImageCount = db.Queryable<Attachment>()
                    .Where(att => att.Status == Status.Enable)
                    .Where(att => hsocuuids.Contains(att.BusinessId))
                    .GroupBy(att => att.BusinessId)
                    .Select(att => att.BusinessId)
                    .Count()
                    ;

                // 执行统计查询
                var statistics = new CommentStatisticsResult
                {
                    // 计算评论总数
                    TotalCount = query.Count(),

                    ImageCount = ImageCount,

                    // 计算平均评分（使用默认值0防止除零错误）
                    AverageRating = query.Any()
                ? Math.Round(query.Sum(hsoc => (int)hsoc.StarRating) / (decimal)query.Count(), 2)
                : 0,

                    // 计算各星级评分的数量分布
                    RatingDistribution = new Dictionary<int, int>
                    {
                        { 1, query.Count(hsoc => hsoc.StarRating == StarRating.OneStar) },
                        { 2, query.Count(hsoc => hsoc.StarRating == StarRating.TwoStars) },
                        { 3, query.Count(hsoc => hsoc.StarRating == StarRating.ThreeStars) },
                        { 4, query.Count(hsoc => hsoc.StarRating == StarRating.FourStars) },
                        { 5, query.Count(hsoc => hsoc.StarRating == StarRating.FiveStars) }
                    }
                };

                return Success(statistics);
            }
            catch (Exception ex)
            {
                return Error("获取评论统计信息失败，请稍后重试");
            }
        }

        /// <summary>
        /// 获取服务订单
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public ResponseModel GetOrder(GetOrderInfo info)
        {
            int total = 0;
            var data = db.Queryable<HomeServiceOrder>()
                .Where(hso => hso.IsDeleted == Status.Disable)
                .WhereIF(info.OrderStatus.HasValue, hso => hso.OrderStatus == info.OrderStatus)
                .OrderBy(hso => hso.CreateTime,OrderByType.Desc)
                .ToPageList(info.PageNumber, info.PageSize, ref total)
                ;

            var uuids = data.Select(x => x.ProductUUID).Distinct().ToList();

            List<HomeServiceProduct> hsps =  db.Queryable<HomeServiceProduct>()
                .Where(hsp => uuids.Contains(hsp.UUID))
                .ToList();

            //商品id
            var hspsuuids = hsps.Select(x => x.UUID).ToList();

            List<HomeServiceProductSpecification> hspss = db.Queryable<HomeServiceProductSpecification>()
                .Where(hspss => hspsuuids.Contains(hspss.HomeServiceProductUUID))
                .ToList()
                ;

            foreach (var item in data)
            {
                HomeServiceProduct hsp = hsps.Where(x => x.UUID == item.ProductUUID).First();
                var hspsst = hspss.Where(x => x.HomeServiceProductUUID == hsp.UUID).FirstOrDefault();
                item.ProductName = hsp.Title;
                item.Image = hsp.ImageUrl;
                item.Product = hsp;
                item.ProductSpecification = hspsst;
            }

            return PageSuccess(info.PageNumber, info.PageSize, total, data);
        }

        /// <summary>
        /// 拼团成功
        /// </summary>
        /// <param name="OrderUUID"></param>
        /// <returns></returns>
        public void GroupSuccess(Guid ProductUUID, DateTime GroupDate)
        {
            try
            {
                db.BeginTran();
                // 更新拼团参与者状态
                db.Updateable<HomeServiceProductGroupParticipant>()
                    .SetColumns(hspgp => new HomeServiceProductGroupParticipant { Status = GroupParticipantStatus.GroupSuccess, UpdateTime = DateTime.Now, UpdateUserUUID = UserUUID })
                    .Where(hspgp => hspgp.ExpireTime > DateTime.Now)            //未过期
                    .Where(hspgp => hspgp.Status == GroupParticipantStatus.Paid) //已支付
                    .Where(hspgp => hspgp.GroupDate == GroupDate)                //所有拼团组同一日期
                    .Where(hspgp => hspgp.HomeServiceProductUUID == ProductUUID)
                    .ExecuteCommand();
                db.CommitTran();
            }
            catch (Exception)
            {
                db.RollbackTran();
                throw;
            }
        }
    }
}
